package org.pvt.gui;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.pvt.R;
import org.pvt.model.Expense;
import org.pvt.model.Model;
import org.pvt.model.Models;

/**
 * @author Pavel Talanov
 */
public final class ExpenseCursorAdapter extends CursorAdapter {

    @NotNull
    private final Context context;

    public ExpenseCursorAdapter(@NotNull Context context, @NotNull Cursor c) {
        super(context, c);
        this.context = context;
    }

    @Override
    public View newView(final Context context, Cursor cursor, ViewGroup parent) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.expense, parent, false);
        setUpView(cursor, view);
        return view;
    }

    private void setUpView(@NotNull Cursor cursor, @NotNull View view) {
        int commentIndex = cursor.getColumnIndex(Expense.COMMENT);
        int categoryIdIndex = cursor.getColumnIndex(Model.referenceById(Models.Category));
        int totalIndex = cursor.getColumnIndex(Expense.TOTAL);

        String comment = cursor.getString(commentIndex);
        ((TextView) view.findViewById(R.id.expenseComment)).setText(comment);
        long categoryId = cursor.getLong(categoryIdIndex);
        String categoryName = Models.Category.getNameById(categoryId, context);
        ((TextView) view.findViewById(R.id.expenseCategory)).setText(categoryName);
        float amount = cursor.getFloat(totalIndex);
        ((TextView) view.findViewById(R.id.expenseAmount)).setText(UIUtils.floatToText(amount, false));
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        //do nothing
    }
}
